package com.ruoyi.web.controller.member;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.yijing.domain.*;
import com.ruoyi.yijing.service.ICustomerInfoAccountService;
import com.ruoyi.yijing.service.ICustomerInfoAccountTokenService;
import com.ruoyi.yijing.service.ICustomerInfoService;
import com.ruoyi.yijing.service.IYjPlatformInfoService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/member/login")
public class LoginController extends Base {


    @Autowired
    private ICustomerInfoAccountService customerInfoAccountService;


    @Autowired
    private IYjPlatformInfoService platformInfoService;

    @Autowired
    private ICustomerInfoService customerInfoService;


    /**
     * 小程序登录
     *
     * @param
     * @return
     */
    @GetMapping(value = "appletLogin")
    public AjaxResult wechatLogin(CustomerInfoAccountVo customerInfoAccountVo) {
        customerInfoAccountVo.setAppId(getAppId());

        if (StringUtils.isEmpty(customerInfoAccountVo.getAppId())){
            throw new ServiceException("缺少appId参数");
        }
        if (StringUtils.isEmpty(customerInfoAccountVo.getCode())){
            throw new ServiceException("缺少code参数");
        }

        YjPlatformInfo platformInfo = platformInfoService.selectYjPlatformInfoByAuthorizerAppid(customerInfoAccountVo.getAppId());
        if (platformInfo == null || !platformInfo.getDataStatus().equals("1")){
            throw new ServiceException("没有找到平台资料");
        }
        logger.info("请求参数code=>" + customerInfoAccountVo.getCode());
        //String rst = HttpUtil.get("https://api.weixin.qq.com/sns/component/jscode2session?appid=" + customerInfoAccountVo.getAppid() + "&js_code=" + customerInfoAccountVo.getCode() + "&grant_type=authorization_code&component_appid=" + wechatPlatformService.appId + "&component_access_token=" + wechatPlatformService.getApiComponentToken());
        String rst = HttpUtil.get("https://api.weixin.qq.com/sns/jscode2session?appid=" + platformInfo.getAuthorizerAppid()
                + "&js_code=" + customerInfoAccountVo.getCode() + "&grant_type=authorization_code&secret=" + platformInfo.getAppSecret());
        logger.info("获取openid结果为：" + rst);
        //rst = "{\"openid\":\"liuhj\"}";
        JSONObject categoryListObj = JSONObject.parseObject(rst);
        logger.info("调用小程序登录返回值:" + categoryListObj);
        if (!StringUtils.isEmpty(categoryListObj.getString("openid"))) {
            CustomerInfoAccountVo customerInfoAccount = new CustomerInfoAccountVo();
            customerInfoAccount.setOpenId(categoryListObj.getString("openid"));
            customerInfoAccount.setSessionKey(categoryListObj.getString("session_key"));
            customerInfoAccount.setUnionid(categoryListObj.getString("unionid"));
            logger.info("=====获取到分享者token=>" + customerInfoAccountVo.getShareUserToken() + "======分享者id=>" + customerInfoAccountVo.getSharecustomerUid() + "===");
            if (customerInfoAccountVo.getShareUserToken() != null) {
                customerInfoAccount.setShareUserToken(customerInfoAccountVo.getShareUserToken());
            }
            if (customerInfoAccountVo.getSharecustomerUid() != null) {
                customerInfoAccount.setSharecustomerUid(customerInfoAccountVo.getSharecustomerUid());
            }
            customerInfoAccount.setPlatformUid(customerInfoAccountVo.getAppId());
            customerInfoAccount.setAppId(customerInfoAccountVo.getAppId());
            customerInfoAccount.setAccountName(customerInfoAccount.getOpenId());
            String token = customerInfoAccountService.saveCustomerAccountInfo(customerInfoAccount);
            return AjaxResult.success("登录成功", token);
        } else {
            return AjaxResult.error("登录失败，请稍后重试");
        }


    }


    /**
     * 公众号登录
     *
     * @param
     * @return
     */
    @GetMapping(value = "gzhLogin")
    public AjaxResult gzhLogin(CustomerInfoAccountVo customerInfoAccountVo) {
        customerInfoAccountVo.setAppId(getAppId());

        if (StringUtils.isEmpty(customerInfoAccountVo.getAppId())){
            throw new ServiceException("缺少appId参数");
        }
        if (StringUtils.isEmpty(customerInfoAccountVo.getCode())){
            throw new ServiceException("缺少code参数");
        }

        YjPlatformInfo platformInfo = platformInfoService.selectYjPlatformInfoByAuthorizerAppid(customerInfoAccountVo.getAppId());
        if (platformInfo == null || !platformInfo.getDataStatus().equals("1")){
            throw new ServiceException("没有找到平台资料");
        }
        logger.info("请求参数code=>" + customerInfoAccountVo.getCode());
        //String rst = HttpUtil.get("https://api.weixin.qq.com/sns/component/jscode2session?appid=" + customerInfoAccountVo.getAppid() + "&js_code=" + customerInfoAccountVo.getCode() + "&grant_type=authorization_code&component_appid=" + wechatPlatformService.appId + "&component_access_token=" + wechatPlatformService.getApiComponentToken());
        String rst = HttpUtil.get("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + platformInfo.getAuthorizerAppid()
                + "&code=" + customerInfoAccountVo.getCode() + "&grant_type=authorization_code&secret=" + platformInfo.getAppSecret());
        logger.info("获取获取公众号openid结果为：" + rst);
        //rst = "{\"openid\":\"liuhj\"}";
        JSONObject categoryListObj = JSONObject.parseObject(rst);
        logger.info("调用获取公众号登录返回值:" + categoryListObj);
        if (!StringUtils.isEmpty(categoryListObj.getString("openid"))) {
            CustomerInfoAccountVo customerInfoAccount = new CustomerInfoAccountVo();
            customerInfoAccount.setOpenId(categoryListObj.getString("openid"));
            customerInfoAccount.setSessionKey(categoryListObj.getString("access_token"));
            customerInfoAccount.setUnionid(categoryListObj.getString("unionid"));

            rst = HttpUtil.get("https://api.weixin.qq.com/sns/userinfo?access_token="+customerInfoAccount.getSessionKey()+"&openid="+customerInfoAccount.getOpenId()+"&lang=zh_CN");
            logger.info("获取公众号用户信息结果为：" + rst);
            if (StringUtils.isNotEmpty(rst)){
                JSONObject userInfo = JSONObject.parseObject(rst);
                customerInfoAccount.setNickname(userInfo.getString("nickname"));
                customerInfoAccount.setSex(userInfo.getString("sex"));
                customerInfoAccount.setHeadimgurl(userInfo.getString("headimgurl"));
                customerInfoAccount.setCountry(userInfo.getString("country"));
                customerInfoAccount.setProvince(userInfo.getString("province"));
                customerInfoAccount.setCity(userInfo.getString("city"));
            }
            //logger.info("=====获取到分享者token=>" + customerInfoAccountVo.getShareUserToken() + "======分享者id=>" + customerInfoAccountVo.getSharecustomerUid() + "===");
            if (customerInfoAccountVo.getShareUserToken() != null) {
                customerInfoAccount.setShareUserToken(customerInfoAccountVo.getShareUserToken());
            }
            if (customerInfoAccountVo.getSharecustomerUid() != null) {
                customerInfoAccount.setSharecustomerUid(customerInfoAccountVo.getSharecustomerUid());
            }
            customerInfoAccount.setPlatformUid(customerInfoAccountVo.getAppId());
            customerInfoAccount.setAppId(customerInfoAccountVo.getAppId());
            customerInfoAccount.setAccountName(customerInfoAccount.getOpenId());
            String token = customerInfoAccountService.saveCustomerAccountInfo(customerInfoAccount);

            return AjaxResult.success("登录成功", token);
        } else {
            return AjaxResult.error("登录失败，请稍后重试");
        }


    }

    /**
     * app登录
     *
     * @param
     * @return
     */
    @GetMapping(value = "appLogin")
    public AjaxResult appLogin(CustomerInfoAccountVo customerInfoAccountVo) {
        customerInfoAccountVo.setAppId(getAppId());

        if (StringUtils.isEmpty(customerInfoAccountVo.getAppId())){
            throw new ServiceException("缺少appId参数");
        }
        if (StringUtils.isEmpty(customerInfoAccountVo.getPhone())){
            throw new ServiceException("缺少phone参数");
        }

        YjPlatformInfo platformInfo = platformInfoService.selectYjPlatformInfoByAuthorizerAppid(customerInfoAccountVo.getAppId());
        if (platformInfo == null || !platformInfo.getDataStatus().equals("1")){
            throw new ServiceException("没有找到平台资料");
        }
        logger.info("请求参数phone=>" + customerInfoAccountVo.getPhone());


            CustomerInfoAccountVo customerInfoAccount = new CustomerInfoAccountVo();
            customerInfoAccount.setOpenId(customerInfoAccountVo.getPhone());
            //customerInfoAccount.setSessionKey(categoryListObj.getString("access_token"));
            customerInfoAccount.setUnionid(customerInfoAccountVo.getPhone());

            customerInfoAccount.setNickname(customerInfoAccountVo.getPhone());
                //customerInfoAccount.setSex(userInfo.getString("sex"));
                //customerInfoAccount.setHeadimgurl(userInfo.getString("headimgurl"));
                //customerInfoAccount.setCountry(userInfo.getString("country"));
                //customerInfoAccount.setProvince(userInfo.getString("province"));
                //customerInfoAccount.setCity(userInfo.getString("city"));
            customerInfoAccount.setPhone(customerInfoAccountVo.getPhone());

            //logger.info("=====获取到分享者token=>" + customerInfoAccountVo.getShareUserToken() + "======分享者id=>" + customerInfoAccountVo.getSharecustomerUid() + "===");
            if (customerInfoAccountVo.getShareUserToken() != null) {
                customerInfoAccount.setShareUserToken(customerInfoAccountVo.getShareUserToken());
            }
            if (customerInfoAccountVo.getSharecustomerUid() != null) {
                customerInfoAccount.setSharecustomerUid(customerInfoAccountVo.getSharecustomerUid());
            }
            customerInfoAccount.setPlatformUid(customerInfoAccountVo.getAppId());
            customerInfoAccount.setAppId(customerInfoAccountVo.getAppId());
            customerInfoAccount.setAccountName(customerInfoAccount.getOpenId());
            customerInfoAccount.setHeadimgurl("https://images.tongkeer.com/yijing/logo.png");
            String token = customerInfoAccountService.saveCustomerAccountInfo(customerInfoAccount);

            return AjaxResult.success("登录成功", token);



    }



}
